package com.example.employeemanagement.service.impl;

import com.example.employeemanagement.dto.GetEmployeeById;
import com.example.employeemanagement.dto.InfoDto;
import com.example.employeemanagement.entry.Department;
import com.example.employeemanagement.entry.Employee;
import com.example.employeemanagement.entry.Position;
import com.example.employeemanagement.entry.Role;
import com.example.employeemanagement.mapper.DepartmentMapper;
import com.example.employeemanagement.mapper.EmployeeMapper;
import com.example.employeemanagement.mapper.PositionMapper;
import com.example.employeemanagement.mapper.RoleMapper;
import com.example.employeemanagement.service.EmployeeService;
import com.example.employeemanagement.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public List<Employee> getAllEmployees() {
        return employeeMapper.getAllEmployees();
    }

    @Override
    public String addEmployee(Employee employee) {
        // 检查 position_id 是否存在于 position 表中
        boolean positionExists = positionMapper.existsById(employee.getPosition_id());
        if (!positionExists) {
            return "插入失败：职位 ID " + employee.getPosition_id() + " 不存在。";
        }
        employeeMapper.addEmployee(employee);
        return "员工添加成功";
    }

    @Override
    public Optional<GetEmployeeById> getEmployeeById(Integer id) {
        Optional<Employee> emp = employeeMapper.getEmployeeById(id);
        
        if (emp.isEmpty()) {
            return Optional.empty();
        }
        
        Employee employee = emp.get();
        GetEmployeeById dto = new GetEmployeeById();
        
        // 将Employee实体的非敏感字段复制到DTO中
        dto.setEmployeeId(employee.getEmployee_id());
        dto.setFirst_name(employee.getFirst_name());
        dto.setLast_name(employee.getLast_name());
        dto.setEmail(employee.getEmail());
        dto.setPhoneNumber(employee.getPhone_number());
        dto.setHireDate(employee.getHire_date());
        dto.setPositionId(employee.getPosition_id());
        dto.setSalary(employee.getSalary());
        dto.setUsername(employee.getUsername());
        dto.setRoleId(employee.getRoleId());
        dto.setDepartment_id(employee.getDepartment_id());
        dto.setAvator(employee.getAvator());
        
        return Optional.of(dto);
    }

    @Override
    public String updateEmployee(Integer id, Employee updatedEmployee) {
        // 检查员工是否存在
        Optional<Employee> existingEmployee = employeeMapper.getEmployeeById(id);
        if (existingEmployee.isEmpty()) {
            return "更新失败：员工ID " + id + " 不存在。";
        }
        
        // 设置ID确保更新正确的记录
        updatedEmployee.setEmployee_id(id);
        
        // 保留原有的敏感字段和必要字段
        Employee original = existingEmployee.get();
        
        // 创建一个新的Employee对象，只包含可以修改的字段：用户名、手机号码、邮箱地址和头像
        Employee employeeToUpdate = new Employee();
        employeeToUpdate.setEmployee_id(id);
        
        // 设置用户名 - 如果为空则保留原值
        if (updatedEmployee.getUsername() == null || updatedEmployee.getUsername().isEmpty()) {
            employeeToUpdate.setUsername(original.getUsername());
        } else {
            employeeToUpdate.setUsername(updatedEmployee.getUsername());
        }
        
        // 设置手机号码 - 如果为空则保留原值
        if (updatedEmployee.getPhone_number() == null || updatedEmployee.getPhone_number().isEmpty()) {
            employeeToUpdate.setPhone_number(original.getPhone_number());
        } else {
            employeeToUpdate.setPhone_number(updatedEmployee.getPhone_number());
        }
        
        // 设置邮箱地址 - 如果为空则保留原值
        if (updatedEmployee.getEmail() == null || updatedEmployee.getEmail().isEmpty()) {
            employeeToUpdate.setEmail(original.getEmail());
        } else {
            employeeToUpdate.setEmail(updatedEmployee.getEmail());
        }
        
        // 设置头像 - 如果为空则保留原值
        if (updatedEmployee.getAvator() == null || updatedEmployee.getAvator().isEmpty()) {
            employeeToUpdate.setAvator(original.getAvator());
        } else {
            employeeToUpdate.setAvator(updatedEmployee.getAvator());
        }
        
        // 执行更新 - 只更新用户名、手机号码、邮箱地址和头像
        int result = employeeMapper.updateEmployee(id, employeeToUpdate);
        return result > 0 ? "员工信息更新成功" : "员工信息更新失败";
    }

    @Override
    public String deleteEmployee(Integer id) {
//        int result = employeeMapper.deleteEmployee(id);
//        return result > 0 ? "Employee deleted successfully" : "Employee not found";
        return "";
    }

    @Override
    public InfoDto getEmployeeInfo(String token) {
        // 从token中提取用户名
        String username = jwtUtil.extractUsername(token);

        // 验证token是否有效
        if (username == null) {
            throw new IllegalArgumentException("无效的token");
        }
        
        // 根据用户名查询员工信息
        Employee employee = employeeMapper.findUserByUserName(username);
        
        // 如果员工不存在，抛出异常
        if (employee == null) {
            throw new IllegalArgumentException("未找到该用户信息");
        }
        
        // 创建InfoDto对象并设置属性
        InfoDto infoDto = new InfoDto();
        infoDto.setEmployeeId(employee.getEmployee_id());
        infoDto.setName(employee.getLast_name() + employee.getFirst_name()); // 合并姓名
        infoDto.setEmail(employee.getEmail());
        infoDto.setPhoneNumber(employee.getPhone_number());
        infoDto.setHireDate(employee.getHire_date());

        // 通过职位id 拿到对应的职位记录
        Position position = positionMapper.getPositionById(employee.getPosition_id());
        // 将职位记录的职位名称设置给InfoDto对象
        infoDto.setPosition(position.getPosition_name());

        infoDto.setSalary(employee.getSalary());
        infoDto.setUsername(employee.getUsername());

        // 获取员工角色
        Role role = roleMapper.getRoleById(employee.getRoleId());
        infoDto.setRole(role.getRoleName());

        // 获取员工部门
        Department department = departmentMapper.getDepartmentById(employee.getDepartment_id());
        infoDto.setDepartment(department.getDepartment_name());

        infoDto.setAvator(employee.getAvator());
        
        return infoDto;
    }
}